<template>
  <div class="app-container">
    <!-- 搜索工作栏 领料 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="单据编号" prop="storageOrderNo">
        <el-input v-model="queryParams.storageOrderNo" placeholder="请输入单据编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="来源类型" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择来源类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_SOURCE_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="来源单号" prop="sourceNo">
        <el-input v-model="queryParams.sourceNo" placeholder="请输入来源单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.OUTBOUND_TYPE)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="出库仓库" prop="outWarehouseId">
        <treeselect v-model="queryParams.outWarehouseId" :options="warehouseTree" :normalizer="normalizerW"
                    placeholder="选择出库仓库" style="width: 180px" @select="onWarehouseChange"/>
      </el-form-item>
      <el-form-item label="出库库位" prop="outStoreId">
        <el-select v-model="queryParams.outStoreId" placeholder="请选择出库库位" clearable size="small"
                   style="width: 180px">
          <el-option v-for="location in locationList" :key="location.id" :label="location.storageLocationName"
                     :value="location.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入库仓库" prop="inWarehouseId">
        <treeselect v-model="queryParams.inWarehouseId" :options="warehouseTree" :normalizer="normalizerW"
                    placeholder="选择入库仓库" style="width: 180px" @select="onWarehouseInChange"/>
      </el-form-item>
      <el-form-item label="入库库位" prop="inStoreId">
        <el-select v-model="queryParams.inStoreId" placeholder="请选择入库库位" clearable size="small"
                   style="width: 180px">
          <el-option v-for="location in locationInList" :key="location.id" :label="location.storageLocationName"
                     :value="location.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择单据状态" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.OUT_STATE)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['warehouse:order-requisition:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['warehouse:order-requisition:export']">导出
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="isEmpty(checkedIds)"-->
<!--          @click="handleDeleteBatch"-->
<!--          v-hasPermi="['warehouse:order-requisition:delete']"-->
<!--        >-->
<!--          批量删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :row-key="getRowKey"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="expand">
        <template v-slot="props">
          <el-table :data="props.row.materialList || []" border style="width: 98%;margin: 0 auto" header-row-class-name="custom-header-row">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="materialName" label="物料名称" align="center" />
            <el-table-column prop="materialNo" label="物料编码" align="center" />
            <el-table-column prop="basicUnit" label="单位" align="center" />
            <el-table-column prop="batchNo" label="批次号" align="center" />
            <el-table-column prop="quantity" label="数量" align="center" />
            <el-table-column prop="alreadyQuantity" label="入库数量" align="center" />
            <el-table-column label="" align="center" class-name="small-padding fixed-width" width="80">
              <template v-slot="scope">
                <el-button :disabled="scope.row.status==4" size="mini" type="text" icon="el-icon-edit" @click="inOrOut(scope.row,props.row)">入库
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55"/>
      <el-table-column label="单据编号" align="center" prop="storageOrderNo"/>
      <el-table-column label="来源类型" align="center" prop="sourceType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.QUALITY_SOURCE_TYPE" :value="scope.row.sourceType"/>
        </template>
      </el-table-column>
      <el-table-column label="来源单号" align="center" prop="sourceNo"/>
      <el-table-column label="业务类型" align="center" prop="businessTypeName"/>
      <el-table-column label="出库仓库" align="center" prop="outWarehouseName"/>
      <el-table-column label="出库库位" align="center" prop="outStoreName"/>
      <el-table-column label="入库仓库" align="center" prop="inWarehouseName"/>
      <el-table-column label="入库库位" align="center" prop="inStoreName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.OUT_STATE, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领料人" align="center" prop="applicantUserName"/>
      <el-table-column label="创建者" align="center" prop="creator"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
             <el-button size="mini" type="text" icon="el-icon-tickets" @click="openForm(scope.row.id, true)">详情
              </el-button>
          <el-button v-if="scope.row.status !== 3" size="mini" type="text" icon="el-icon-document-checked" @click="overForm(scope.row)">完结
          </el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['warehouse:order-requisition:update']">修改
          </el-button> -->
<!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                     v-hasPermi="['warehouse:order-requisition:delete']">删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <OrderForm ref="formRef" @success="getList"/>

    <!-- 出库弹框 -->
      <el-dialog
        :title="'入库操作'"
        :visible.sync="outDialogVisible"
        width="1000px"
        :close-on-click-modal="false"
        @close="handleOutDialogClose"
      >
        <el-form :model="outFormData" ref="outFormRef" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物料名称" prop="materialName">
                <el-input v-model="outFormData.materialName" readonly style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批次号" prop="batchNo">
                <el-input v-model="outFormData.batchNo" readonly style="width: 100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库仓库" prop="inWarehouseId">
                <treeselect
                  v-model="outFormData.inWarehouseId"
                  :options="warehouseTree"
                  :normalizer="normalizerW"
                  placeholder="选择入库仓库"
                  style="width: 100%"
                  @select="handleOutWarehouseChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库库位" prop="inStoreId">
                <el-select
                  v-model="outFormData.inStoreId"
                  placeholder="请选择入库库位"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="location in inOrOutIocationList"
                    :key="location.id"
                    :label="location.storageLocationName"
                    :value="location.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数量" prop="quantity">
                <el-input
                  v-model.number="outFormData.quantity"
                  placeholder="请输入入库数量"
                  style="width: 100%"
                  type="number"
                  :min="0"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleOutDialogClose">取消</el-button>
          <el-button type="primary" @click="handleOutConfirm">确认</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import * as OrderApi from '@/api/warehouse/order';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'
import OrderForm from './OrderForm.vue';
import * as WarehouseApi from "@/api/storage/warehouse";
import * as LocationApi from "@/api/storage/location";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "OrderRequisition",
  components: {
    OrderForm,
    Treeselect
  },
  data() {
    return {
      // 仓库树数据
      warehouseTree: [],
      // 仓库树加载状态
      treeLoading: false,
      // 库位列表
      locationList: [],
      locationInList: [],
      inOrOutIocationList: [], // 出库专用库位列表
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库单据列表
      // 出库弹框相关
      outDialogVisible: false,
      outFormData: {
        id: null,
        materialId: null,
        materialName: '',
        batchNo: '',
        outWarehouseId: null,
        outStoreId: null,
        quantity: 0
      },
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        storageOrderNo: null,
        sourceType: null,
        sourceTypeName: null,
        sourceNo: null,
        businessType: null,
        businessTypeName: null,
        outWarehouseId: null,
        outWarehouseName: null,
        outStoreId: null,
        outStoreName: null,
        inWarehouseId: null,
        inWarehouseName: null,
        inStoreId: null,
        inStoreName: null,
        status: null,
        createTime: [],
        orderType:'1'
      },
    };
  },
  created() {
    this.getList();
    this.getWarehouseTree();

  },
  methods: {
    // 打开入库弹框
    inOrOut(child,father){
      // 初始化表单数据
      this.outFormData = {
        id: child.id,
        materialId: child.materialId,
        materialName: child.materialName,
        batchNo: child.batchNo || '',
        inWarehouseId: father.inWarehouseId,
        inStoreId: father.inStoreId,
        quantity: child.quantity
      };

      // 如果有选择仓库，加载对应的库位列表
      if (father.inWarehouseId) {
        this.getInOrOutLocationList(father.inWarehouseId);
      } else {
        this.inOrOutIocationList = [];
      }

      // 显示弹框
      this.outDialogVisible = true;
    },

    // 出库弹框中仓库选择变化
    async handleOutWarehouseChange(warehouseId) {
      this.outFormData.inStoreId = null;
      if (warehouseId) {
        await this.getInOrOutLocationList(warehouseId.id);
      } else {
        this.inOrOutIocationList = [];
      }
    },

    // 获取出库弹框专用库位列表
    async getInOrOutLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.inOrOutIocationList = res.data.list;
      } catch (error) {
        console.error('获取出库库位列表失败:', error);
        this.inOrOutIocationList = [];
      }
    },

    // 关闭出库弹框
    handleOutDialogClose() {
      this.outDialogVisible = false;
      this.$refs.outFormRef && this.$refs.outFormRef.resetFields();
    },

    // 确认出库
    async handleOutConfirm() {
      try {
        // 构建请求参数
        const params = {
          id: this.outFormData.id,
          inStoreId: this.outFormData.inStoreId,
          materialId: this.outFormData.materialId,
          batchNo: this.outFormData.batchNo,
          quantity: this.outFormData.quantity
        };

        // 调用出库接口
        await OrderApi.inOrOut(params);

        // 关闭弹框
        this.outDialogVisible = false;

        // 刷新列表
        this.getList();

        // 提示成功
        this.$modal.msgSuccess('入库成功');
      } catch (error) {
      }
    },

    // 完结单据
    async overForm(row) {
      try {
        // 二次确认对话框
        await this.$confirm('确定要完结该单据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 调用完结接口，传递整行数据
        await OrderApi.finish(row);

        // 刷新列表
        this.getList();

        // 提示成功
        this.$modal.msgSuccess('单据完结成功');
      } catch (error) {
        // 如果是用户取消确认，不显示错误信息
        if (error !== 'cancel') {
          console.error('单据完结失败:', error);
          this.$modal.msgError('单据完结失败');
        }
      }
    },
    /** 获取行数据的唯一标识 */
    getRowKey(row) {
      return row.id;
    },
    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        this.treeLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.$modal.msgError('获取仓库树数据失败');
      } finally {
        this.treeLoading = false;
      }
    },


    /** 树节点标准化处理 */
    normalizerW(node) {
      const result = {
        id: node.id,
        label: node.warehouseName,
        children: undefined
      };
      // 只有当children存在且不为undefined且长度大于0时才添加该字段
      if (node.children && node.children.length > 0) {
        result.children = node.children;
      }
      return result;
    },

    /** 仓库选择变化时触发 */
    async onWarehouseChange(warehouseId) {
      this.queryParams.outStoreId = null;
      if (warehouseId) {
        await this.getLocationList(warehouseId.id);
      } else {
        this.locationList = [];
      }
    },
    /** 仓库选择变化时触发 */
    async onWarehouseInChange(warehouseId) {
      this.queryParams.inStoreId = null;
      if (warehouseId) {
        await this.getLocationInList(warehouseId.id);
      } else {
        this.locationList = [];
      }
    },

    /** 根据仓库ID获取库位列表 */
    async getLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationList = [];
      }
    },

    /** 根据仓库ID获取库位列表 */
    async getLocationInList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationInList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationInList = [];
      }
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await OrderApi.getOrderPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id, isDetail = false) {
      this.$refs["formRef"].open(id, isDetail);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除仓库单据编号为"' + id + '"的数据项?')
      try {
        await OrderApi.deleteOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除仓库单据 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await OrderApi.deleteOrderList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有仓库单据数据项?');
      try {
        this.exportLoading = true;
        const data = await OrderApi.exportOrderExcel(this.queryParams);
        this.$download.excel(data, '仓库单据.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
<style scoped>
/* 使用深度选择器确保样式能正确应用到子表格表头 */
::v-deep .custom-header-row th {
  background-color: #659cdb !important;
  color: white;
}

/* 确保表头单元格也应用样式 */
::v-deep .custom-header-row .cell {
  color: white;
}
</style>
